package repositories

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"nodeseller/datamodels"
	mymongo "nodeseller/mongo"
)

type ITopUp interface {
	//连接数据库
	Conn()(error)
	//插入数据库
	Insert(bill *datamodels.TopUp)(error)
	//查询所有待处理缴费
	FindWaitCheck(string)([]datamodels.TopUp,error)
	//查询所有处理的缴费
	FindFinedCheck(string)([]datamodels.TopUp,error)
}

type TopUpManager struct {
	mongoDataColletion mymongo.Collection
}
func NewTopUpManager()ITopUp  {
	mongodb,err := mymongo.Get()
	if err != nil{
		return nil
	}
	return &TopUpManager{
		mongodb.Collection("topup"),
	}
}
//创建连接
func (p *TopUpManager)Conn()(error)  {
	if p.mongoDataColletion == nil{
		mongodb,err := mymongo.Get()
		if err != nil{
			return err
		}
		p.mongoDataColletion = mongodb.Collection("topup")
	}
	return nil
}
//创建充值订单
func (p *TopUpManager)Insert(bill *datamodels.TopUp)(error)  {
	//判断连接是否存在
	if err := p.Conn();err != nil{
		return  err
	}
	_,err := p.mongoDataColletion.InsertOne(context.TODO(),bill)
	if err != nil{
		return err
	}
	return nil
}
//查询所有待处理缴费
func (p *TopUpManager)FindWaitCheck(phonenumber string)(result []datamodels.TopUp,err error)  {
	//判断连接是否存在
	if err := p.Conn();err != nil{
		return  result,err
	}
	cur,err := p.mongoDataColletion.Find(context.TODO(),bson.M{"phonenumber":phonenumber,"check":false})
	if err != nil{
		return  result,err
	}
	for cur.Next(context.TODO()){
		var elem datamodels.TopUp
		err := cur.Decode(&elem)
		if err != nil{
			return result,err
		}
		result = append(result,elem)
	}
	return result,nil
}
//查询所有处理的缴费
func (p *TopUpManager)FindFinedCheck(phonenumber string)(result []datamodels.TopUp,err error){
	//判断连接是否存在
	if err := p.Conn();err != nil{
		return  result,err
	}
	cur,err := p.mongoDataColletion.Find(context.TODO(),bson.M{"phonenumber":phonenumber,"check":true})
	if err != nil{
		return  result,err
	}
	for cur.Next(context.TODO()){
		var elem datamodels.TopUp
		err := cur.Decode(&elem)
		if err != nil{
			return result,err
		}
		result = append(result,elem)
	}
	return result,nil
}